//
//  STMShopManagementViewController.m
//  StoreManagement
//
//  Created by centling on 16/5/13.
//  Copyright © 2016年 alfred. All rights reserved.
//

#import "STMShopManagementViewController.h"
#import "STMLoginViewController.h"

@interface STMShopManagementViewController ()<UIGestureRecognizerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *qqTextField;
@property (weak, nonatomic) IBOutlet UITextField *wangwangTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UIImageView *shopIconImageView;

@property (nonatomic, strong) NSData *avatarData;

@end

@implementation STMShopManagementViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self customNavigationTitle:@"店铺管理"];
    UIButton *saveButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    saveButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [saveButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageClick)];
    self.shopIconImageView.userInteractionEnabled = YES;
    [self.shopIconImageView addGestureRecognizer:tap];
    self.phoneTextField.delegate = self;
    
//    self.shopIconImageView.layer.borderColor = MAINGRAYCOLOR.CGColor;
//    self.shopIconImageView.layer.borderWidth = 1;
    self.shopIconImageView.layer.cornerRadius = 30;
    self.shopIconImageView.layer.masksToBounds = YES;
    [self customTextField:self.qqTextField placeholder:@"请输入QQ" keyboard:UIKeyboardTypeNumberPad];
    [self customTextField:self.wangwangTextField placeholder:@"请输入旺旺" keyboard:UIKeyboardTypeASCIICapable];
    [self customTextField:self.phoneTextField placeholder:@"请输入手机号" keyboard:UIKeyboardTypeNumberPad];
        
    [self loadViewData];
}


- (void)loadViewData {
    [SVProgressHUD showWithStatus:@"加载中..."];
    [STMNetworkAPI getShopInfoWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                              success:^(STMShopInfoModel *result) {
                                  if ([result.code isEqualToString:@"200"]) {
                                      [SVProgressHUD dismiss];
                                      self.qqTextField.text = result.result.store_qq;
                                      self.wangwangTextField.text = result.result.store_ww;
                                      self.phoneTextField.text = result.result.store_phone;
                                      [self.shopIconImageView sd_setImageWithURL:[NSURL URLWithString:result.result.store_banner] placeholderImage:nil];
                                      
                                  } else if ([result.code isEqualToString:@"401"]) {
                                      [GlobalUtil presentLoginVC];
                                  } else {
                                      [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                  }
                              }
                              failure:^(NSError *err) {
                                  [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                              }];
}

- (void)imageClick {
    [self.view endEditing:YES];
    
    CTActionSheet *actionSheet = [CTActionSheet actionSheetWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相机相册选择" HandleBlock:^(int btnIndex) {
        if (btnIndex == 0) {
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
                picker.delegate = self;
                //                picker.allowsEditing = YES;//设置可编辑
                picker.sourceType = sourceType;
                [self presentViewController:picker animated:YES completion:^{
                    
                }];//进入照相界面
            }
            
        }else if (btnIndex == 1){
            UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            }
            pickerImage.delegate = self;
            //            pickerImage.allowsEditing = YES;
            [self presentViewController:pickerImage animated:YES completion:^{
                
            }];
            
        }else{
            //AWLog(@"点击了取消");
        }
    }];
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    if ([window.subviews containsObject:self.view]) {
        [actionSheet showInView:self.view];
    } else {
        [actionSheet showInView:window];
    }
}



#pragma 获取相片后执行的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

    CTActionSheet *actionSheet = [CTActionSheet actionSheetWithTitle:@"确认选择该照片吗" cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:nil HandleBlock:^(int btnIndex) {

        if (btnIndex == 0) {
            UIImage *originalImage =  (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
            if(!originalImage){
                originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
            }
            self.shopIconImageView.image = originalImage;
            self.avatarData = UIImageJPEGRepresentation(originalImage, 0.5);
            [picker dismissViewControllerAnimated:YES completion:^{

            }];
        }
    }];
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    if ([window.subviews containsObject:self.view]) {
        [actionSheet showInView:self.view];
    } else {
        [actionSheet showInView:window];
    }

}

- (void)saveAction {
    if (![GlobalUtil validateMobile:self.phoneTextField.text]) {
        [GlobalUtil HUDShowMessage:@"请输入合法的手机号" addedToView:self.view];
        return;
    }
    self.avatarData = UIImageJPEGRepresentation(self.shopIconImageView.image, 0.5);
    [SVProgressHUD showWithStatus:@"加载中..."];
    [STMNetworkAPI shopInfoEditWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                           storeAvatar:self.avatarData
                                    qq:self.qqTextField.text
                                    ww:@""
                                 phone:self.phoneTextField.text
                               success:^(STMShopInfoModel *result) {
                                   [SVProgressHUD dismiss];
                                   if ([result.code isEqualToString:@"200"]) {
                                       [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
//                                       self.qqTextField.text = result.result.store_qq;
//                                       self.wangwangTextField.text = result.result.store_ww;
//                                       self.phoneTextField.text = result.result.store_phone;
//                                       [self.shopIconImageView sd_setImageWithURL:[NSURL URLWithString:result.result.store_banner] placeholderImage:nil];
                                       [self loadViewData];
                                   } else if ([result.code isEqualToString:@"401"]) {
                                       [GlobalUtil presentLoginVC];
                                   } else {
                                       [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                   }
                               }
                               failure:^(NSError *err) {
                                   [SVProgressHUD dismiss];
                                   [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                               }];
}


- (void)customTextField:(UITextField *)textField placeholder:(NSString *)placeholderText keyboard:(UIKeyboardType)keyboardType {
    textField.layer.borderWidth = 0;
    textField.placeholder = placeholderText;
    textField.keyboardType = keyboardType;
    
}

#pragma mark --UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([self.phoneTextField isFirstResponder]) {
        if (string.length - range.length + textField.text.length > 11) {
            return NO;
        }
        //删除键可用
        if([string isEqualToString:@""]){
            return YES;
        }
        //只输入数字
        return [GlobalUtil validateNumOnly:string digits:11];
    }
    return YES;
}


- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
